<template>
  <el-dialog
      title="编辑用户"
      :visible.sync="open"
      width="800px"
      append-to-body
      @close="resetForm"
  >
    <div class="dialog__header">基本信息</div>
<!--        {{JSON.stringify(form,null,4)}}-->
    <el-form ref="form" :rules="rules" :model="form" label-width="150px" style='margin-top: 20px;'>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="name" >
            <el-input @input="grtAccount"
                      v-model="form.name"
                      placeholder="请输入姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户组织类型" prop="type" >
            <el-select v-model="form.type" disabled placeholder="请选择" disabled style="width:100%">
              <el-option label="外部" :value="0"/>
              <el-option label="内部" :value="1"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户编码" prop="account">
            <el-input disabled
                      v-model="form.account"
                      placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户手机号" prop="phone">
            <el-input v-model="form.phone" maxlength="11" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="form.idType" disabled placeholder="请选择" style="width:100%">
              <el-option label="统一社会信用代码" :value="1" />
              <el-option label="身份证" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码" prop="idNo">
            <el-input v-model="form.idNo"  placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属组织" prop="enterpriseId">
            <el-select @change="enterpriseChange" v-model="form.enterpriseId" filterable clearable  placeholder="请选择" style="width:100%">
              <el-option v-for="item in organizationList" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其他组织" prop="enterpriseOtherId">
            <el-select v-model="form.enterpriseOtherId" filterable clearable multiple placeholder="请选择" style="width:100%">
              <el-option v-for="item in organizationListOther"
                         :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="form.createTime" disabled placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <div class="dialog__header" style="margin-bottom:16px;">三方系统账号</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实名状态" prop="status">
            <el-select style="width: 100%" v-model="form.realNameStatus" disabled placeholder="请选择">
              <el-option label="未实名 " :value="0"/>
              <el-option label="已实名 " :value="1"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="5G随意签SaaS账号" prop="status">
            <el-input disabled
                      v-model="form.saasAccountG5"
                      placeholder=""
            />
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  phoneChange,
  idChange,
  emailChange,
  maskPhoneNumber,
  maskEmail, inputWordChange
} from "@/utils/fengwenxin_utils";
import {parseTime} from "@/utils/ruoyi";
import {generateAccount, updateRelativeUser} from "@/api/organizationOuter/userApi";
import {findRelativeEnterpriseList} from "@/api/organizationOuter/etpApi";
import {debounce} from "@/utils";

let defaultForm = {
  id: '',
  name: '',
  account: '',
  status: "1",
  contractAddress: "",
  idType: 1,
  idNo: "",
  type: 0,
  phone:'',
  email:"",
  createTime: '',
  enterpriseId:"",
  enterpriseOtherId:"",
  realNameStatus:"",
  saasAccountG5:""
}
export default {
  components: {},
  data() {
    return {
      form: JSON.parse(JSON.stringify(defaultForm)),
      open: false,
      organizationList:[],
      rules: {
        name: [
          {required: true, message: '请输姓名', trigger: 'change'},
          { validator:inputWordChange, trigger: 'change' },
          {min: 2, max: 50, message: '姓名请输入2-25个字', trigger: 'change'}
        ],
        account: [
          {required: true, message: '还未生成账号', trigger: 'change'},
        ],
        type: [
          {required: true, message: '请选择用户组织类型', trigger: 'change'},
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'change'},
          { validator:phoneChange, trigger: 'blur'},
        ],
        idNo: [
          {  validator:idChange, trigger: 'change' }
        ],
        email: [
          {  validator:emailChange, trigger: 'blur' }
        ],
      }
    };
  },
  computed:{
    organizationListOther(){
      return  this.organizationList.filter(item=> item.value != this.form.enterpriseId)
    }
  },
  created() {
    this.enterpriseList();
  },
  methods: {
    enterpriseChange(val){
      const enterpriseOtherIds = this.form.enterpriseOtherId;
      const index = enterpriseOtherIds.findIndex(ele => ele == val)
      enterpriseOtherIds.splice(index,1)
      // console.log('enterpriseOtherIds',enterpriseOtherIds,index)
      this.form.enterpriseOtherId  = enterpriseOtherIds;
    },
    enterpriseList(){
      findRelativeEnterpriseList({
        pageSize:5000,
        pageNo:1,
      }).then(res => {
        let list = res.data.list || [];
        this.organizationList = list.map(item=>{
          return {
            label:item.name,
            value:Number(item.id)
          }
        })
      }).catch(err => {
        console.log('err', err)
      })
    },
    grtAccount:debounce(function (){
      generateAccount({
        nickname:this.form.name,
        type:'1',
      }).then(res=>{
        this.form.account = res.data;
      }).catch(err=>{
        console.log('err',err)
      })
    }),
    maskPhoneNumber(val) {
      return maskPhoneNumber(val)
    },
    maskEmail(val) {
      return maskEmail(val)
    },
    show(row) {
      // console.log('row',row)
      // this.form = Object.assign(this.form,row)
      this.open = true;
      for (let key in defaultForm) {
        this.form[key] = row[key]
      }
      this.form.createTime = parseTime(this.form.createTime)
      // this.form.phone = maskPhoneNumber(this.form.phone)
      // this.form.email = maskEmail(this.form.email)
      this.form.type = 0;

      if(this.form.enterpriseId===0){
        this.form.enterpriseId = ""
      }
      try {
        if(this.form.enterpriseOtherId){
          const arrs = JSON.parse(this.form.enterpriseOtherId.split(',')) || [];
          this.form.enterpriseOtherId = arrs.map(str=>Number(str))
        }
      }catch{
        this.form.enterpriseOtherId = []
      }


      // console.log('this.form',this.form.enterpriseOtherId)
    },
    submitForm() {
      // console.log('jiek', this.form)
      this.$refs['form'].validate(valid=>{
        if(!valid) return;
        const post_data = Object.assign({},this.form)
        const enterpriseOtherId = post_data.enterpriseOtherId;
        if(enterpriseOtherId.length>0){
          post_data.enterpriseOtherId = JSON.stringify(enterpriseOtherId)
        }else{
          post_data.enterpriseOtherId = '';
        }
        updateRelativeUser(post_data).then((response) => {
          this.$message({
            message: '编辑成功',
            type: 'success'
          });
          this.open = false;
          this.$emit("getList");
        }).catch(err => {
          console.error('err', err)
        });
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 重置按钮操作 */
    resetForm() {
      this.form = JSON.parse(JSON.stringify(defaultForm))
    },
  },
};
</script>
<style lang="less" scoped>
.dialog__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
  font-size: 14px !important;
  font-weight: bold;
  color: #000;
}
</style>
